package com.pc.cloud.utils;

import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;

import java.util.List;

public class QueryUtils {
	public static Query getAbs(Query q) {
	    if (!(q instanceof BooleanQuery)) return q;
	    BooleanQuery bq = (BooleanQuery)q;

	    List<BooleanClause> clauses = bq.clauses();
	    if (clauses.size()==0) return q;


	    for (BooleanClause clause : clauses) {
	      if (!clause.isProhibited()) return q;
	    }

	    if (clauses.size()==1) {
	      // if only one clause, dispense with the wrapping BooleanQuery
	      Query negClause = clauses.get(0).getQuery();
	      // we shouldn't need to worry about adjusting the boosts since the negative
	      // clause would have never been selected in a positive query, and hence would
	      // not contribute to a score.
	      return negClause;
	    } else {
	      BooleanQuery newBq = new BooleanQuery(bq.isCoordDisabled());
	      newBq.setBoost(bq.getBoost());
	      // ignore minNrShouldMatch... it doesn't make sense for a negative query

	      // the inverse of -a -b is a OR b
	      for (BooleanClause clause : clauses) {
	        newBq.add(clause.getQuery(), BooleanClause.Occur.SHOULD);
	      }
	      return newBq;
	    }
	  }
}
